import fs, { Stats } from 'fs';
import path from 'path';
import type { ComponentResolver } from 'unplugin-vue-components';

/**
 *
 * 考虑到utils不同文件中的重名方法/常量几率很高，所以不对utils做自动导入
 * 这里仅做代码遗留
 *
 */

//utils路径
const prefixUtilPath = path.resolve(process.cwd(), 'src/utils');

//别名路径
const aliasPath = '/@/utils';

const primitiveUtilsNames: { [key: string]: { as?: string; from: string; name?: string } } = {};

const root = process.cwd() + '/src/utils';

walkSync(prefixUtilPath, ['.ts'], function (path) {
  // const names = path.split('/');

  const fileContent = fs.readFileSync(path, { encoding: 'utf-8' });
  const targets =
    fileContent.match(/export(\s*)(function|const|type|interface|class)(\s*)(\w+)/gim) || [];
  targets.forEach((s) => {
    const names = s.split(' ');
    const targetName = names[names.length - 1];

    //绝对路径替换成别名路径
    const related = path.replace(root, aliasPath);

    // console.log(s + '    ------------->     ' + related);

    //如果有重名
    if (!primitiveUtilsNames[targetName]) {
      primitiveUtilsNames[targetName] = { as: targetName, from: `${related}` };
    } else {
      //来自不同文件的重名，给出警告
      //来自同个文件就是重载，忽略
      if (primitiveUtilsNames[targetName].from != related) {
        console.log(targetName + '    ------------->     ' + related);
      }
    }
  });
});

export function GllUtilsResolver(): ComponentResolver {
  return {
    //无用
    type: 'component',
    resolve: (name) => {
      return primitiveUtilsNames[name];
    },
  };
}

// nodejs 递归扫描文件
export function walkSync(
  currentDirPath: string,
  fileType: string[],
  callback: (p: string, s: Stats) => void,
) {
  fs.readdirSync(currentDirPath, { withFileTypes: true }).forEach(function (name) {
    const filePath = path.join(currentDirPath, name.name);
    const stat = fs.statSync(filePath);
    if (stat.isFile() && fileType.some((s) => name.name.endsWith(s))) {
      callback(filePath, stat);
    } else if (stat.isDirectory()) {
      walkSync(filePath, fileType, callback);
    }
  });
}

// 不同平台下的路径分割符
export const PlatformSplitChar = process.platform === 'win32' ? '\\' : '/';
